import request, { post, get, put, del } from '../../utils/request.js';
import { showToast } from '../../utils/common.js';

const state = {
  orderList: [],
  currentOrder: null
};

const mutations = {
  SET_ORDER_LIST(state, list) {
    state.orderList = list;
  },
  SET_CURRENT_ORDER(state, order) {
    state.currentOrder = order;
  },
  CLEAR_CURRENT_ORDER(state) {
    state.currentOrder = null;
  }
};

const actions = {
  // 获取订单列表
  async getOrderList({ commit }, params = {}) {
    try {
      const res = await get('/api/order/list', params);
      commit('SET_ORDER_LIST', res);
      return res;
    } catch (error) {
      showToast('获取订单列表失败');
      return [];
    }
  },
  
  // 获取订单详情
  async getOrderDetail({ commit }, id) {
    try {
      const res = await get(`/api/order/detail/${id}`);
      commit('SET_CURRENT_ORDER', res);
      return res;
    } catch (error) {
      showToast('获取订单详情失败');
      return null;
    }
  },
  
  // 创建订单
  async createOrder({ commit }, params) {
    try {
      const res = await post('/api/order/create', params);
      commit('SET_CURRENT_ORDER', res);
      return res;
    } catch (error) {
      showToast('创建订单失败');
      return null;
    }
  },
  
  // 支付订单
  async payOrder({ commit, dispatch }, id) {
    try {
      const res = await put(`/api/order/pay/${id}`);
      showToast('支付成功', 'success');
      // 刷新订单详情
      dispatch('getOrderDetail', id);
      return res;
    } catch (error) {
      showToast('支付失败，请重试');
      return null;
    }
  },
  
  // 确认收货
  async confirmOrder({ commit, dispatch }, id) {
    try {
      const res = await put(`/api/order/confirm/${id}`);
      showToast('确认收货成功', 'success');
      // 刷新订单详情
      dispatch('getOrderDetail', id);
      return res;
    } catch (error) {
      showToast('确认收货失败');
      return null;
    }
  },
  
  // 取消订单
  async cancelOrder({ commit, dispatch }, id) {
    try {
      const res = await put(`/api/order/cancel/${id}`);
      showToast('取消订单成功', 'success');
      // 刷新订单列表
      dispatch('getOrderList');
      return true;
    } catch (error) {
      showToast('取消订单失败');
      return false;
    }
  }
};

const getters = {
  orderList: state => state.orderList,
  currentOrder: state => state.currentOrder,
  pendingPaymentOrders: state => state.orderList.filter(item => item.status === 1),
  pendingDeliveryOrders: state => state.orderList.filter(item => item.status === 2),
  pendingReceiptOrders: state => state.orderList.filter(item => item.status === 3),
  completedOrders: state => state.orderList.filter(item => item.status === 4)
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}; 